package chen.yi.component.mysql.check;

import chen.yi.component.common.exception.BizException;
import chen.yi.component.mysql.enums.TableErrorEnums;
import chen.yi.component.mysql.po.IndexPO;
import chen.yi.component.mysql.utils.TableAttrUtils;
import chen.yi.component.mysql.vo.system.IndexTypeVO;
import cn.hutool.core.util.StrUtil;

import java.util.List;
import java.util.Objects;

import static chen.yi.component.mysql.enums.TableErrorEnums.*;

/**
 * 索引校验
 * @author huat
 **/
public final class IndexCheckUtils extends BaseCheckUtils{
    private IndexCheckUtils() {}

    /**
     * 校验字段是否合法
     * @param indexPOS 索引集合
     */
    public static void checkIndex(final List<IndexPO> indexPOS) {
        indexPOS.forEach(indexPO -> {
            checkIndexName(indexPO.getIndexName());
            checkIndexType(indexPO.getIndexType());
            checkIndexFunction(indexPO.getIndexFunction());
            checkComment(indexPO.getComment());
        });
    }

    /**
     * 校验字段名是否合法
     * @param fieldName 字段名
     */
    private static void checkIndexName(final String fieldName) {
        if (!NAME_PATTERN.matcher(fieldName).matches() || RESERVED_WORDS.contains(fieldName.toUpperCase())) {
            throw new BizException(TableErrorEnums.FIELD_NAME.getCode(), String.format(TableErrorEnums.FIELD_NAME.getMessage(),fieldName));
        }
    }
    /**
     * 校验索引类型是否合法
     * @param indexType 索引类型
     */
    private static void checkIndexType(final String indexType) {
        if (Objects.isNull(indexType)) {
            return;
        }
        //获取索引对象
        IndexTypeVO indexObject = TableAttrUtils.getIndexType();
        List<String> indexTypes = indexObject.getIndexType();
        if(!indexTypes.contains(indexType)) {
            throw new BizException(INDEX_TYPE.getCode(),String.format(INDEX_TYPE.getMessage(),indexType));
        }
    }
    /**
     * 校验索引方法是否合法
     * @param indexFunction 索引方法
     */
    private static void checkIndexFunction(final String indexFunction) {
        if (Objects.isNull(indexFunction)) {
            return;
        }
        //获取索引对象
        IndexTypeVO indexObject = TableAttrUtils.getIndexType();
        List<String> indexFunctions = indexObject.getIndexFunction();
        if(!indexFunctions.contains(indexFunction)) {
            throw new BizException(INDEX_FUNCTION.getCode(),String.format(INDEX_FUNCTION.getMessage(),indexFunction));
        }
    }

    /**
     * 备注校验
     *
     * @param comment 备注内容
     */
    private static void checkComment(String comment) {
        if (StrUtil.isBlank(comment)) {
            throw new BizException(INDEX_COMMENT.getCode(), INDEX_COMMENT.getMessage());
        }
        if (!COMMENT_PATTERN.matcher(comment).matches()) {
            throw new BizException(TableErrorEnums.COMMENT_CONTENT.getCode(), String.format(TableErrorEnums.COMMENT_CONTENT.getMessage(), comment));
        }
    }

}
